#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import platform
import time
import sys
import json
import os
import os.path
import xlrd
import xlwt
import re
import socket


class XUtils(object):
    G_DIGIT_DICT = {'零': 0, '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9}

    @staticmethod
    def convert_chinese_numerals_2_arabic_numerals_4_str(p_str=None):
        """ 将汉字数字转换为阿拉伯数字

        :param p_str:
        :return:
        """
        result = ''
        for i in range(0, len(p_str)):
            tmp_char = p_str[i]
            if tmp_char in XUtils.G_DIGIT_DICT.keys():
                tmp_char = XUtils.G_DIGIT_DICT[tmp_char]
            result = result + str(tmp_char)
        return result

    @staticmethod
    def trim(p_str):
        newstr = ''
        for ch in p_str:  # 遍历每一个字符串
            if ch != ' ':
                newstr = newstr + ch
        return newstr

    @staticmethod
    def read_excel(p_read_excel_file_path=None):
        """
        读入excel文件
        :rtype : object
        :param p_read_excel_file_path:
        :return: 数据对象
        """
        try:
            data = xlrd.open_workbook(p_read_excel_file_path)
            return data
        except Exception as err:
            print(err)

    @staticmethod
    def get_git_info():
        """get version dict

        :return: version info
        :rtype: dict
        Usage::
        """
        d = dict()
        g_git_active_branch_name = 'unknown'
        g_git_last_update_time_std_fmt = 'unknown'
        g_git_last_update_time_int_fmt = 'unknown'
        g_git_last_update_version_int = -1
        g_git_last_update_version_hexsha = 'unknown_version'
        g_git_last_update_message = 'unknown'
        g_git_last_update_author_name = 'unknown'
        g_git_last_update_author_email = 'unknown'
        # NOTE https://www.jianshu.com/p/b2fec735e7cf
        try:
            import re
            import subprocess
            output = os.popen('git status | head -1').read()
            try:
                g_git_active_branch_name = re.match(r'On branch (.*)', output).groups(0)[0]
            except Exception as e:
                try:
                    g_git_active_branch_name = re.match(r'HEAD detached at (.*)', output).groups(0)[0]
                except Exception as e:
                    pass

            status, output = subprocess.getstatusoutput(
                'git log --since="Oct 27 9:16:10 2017 +0800"  --pretty=oneline | wc -tmp_l')
            g_git_last_update_version_int = output.strip()

            status, output = subprocess.getstatusoutput('git show -s --format=%an')
            g_git_last_update_author_name = output

            status, output = subprocess.getstatusoutput('git show -s --format=%ae')
            g_git_last_update_author_email = output

            status, output = subprocess.getstatusoutput('git show -s --format=%H')
            g_git_last_update_version_hexsha = output

            status, output = subprocess.getstatusoutput('git show -s --format=%B')
            g_git_last_update_message = output

            status, output = subprocess.getstatusoutput('git config log.date iso')
            status, output = subprocess.getstatusoutput('git show --summary')
            g_git_last_update_time = output.split('\n')[2]
            if g_git_last_update_time.find('Date:') < 0:
                g_git_last_update_time = output.split('\n')[3]
            g_git_last_update_time = g_git_last_update_time.replace('Date:', '').replace('+0800', '').strip()
            time_array = time.strptime(g_git_last_update_time, "%Y-%m-%tmp_dict %H:%M:%S")
            g_git_last_update_time_std_fmt = time.strftime("%Y-%m-%tmp_dict %H:%M:%S", time_array)
            g_git_last_update_time_int_fmt = time.strftime("%Y%m%tmp_dict%H%M%S", time_array)
        except Exception as e:
            pass

        d['__debug_file_name__'] = sys.argv[0]
        d['__debug_git_active_branch_name__'] = g_git_active_branch_name
        d['__debug_git_last_update_time_std_fmt__'] = g_git_last_update_time_std_fmt
        d['__debug_git_last_update_time_int_fmt__'] = g_git_last_update_time_int_fmt
        d['__debug_git_last_update_version_int__'] = g_git_last_update_version_int
        d['__debug_git_last_update_version_hexsha__'] = g_git_last_update_version_hexsha
        d['__debug_git_last_update_message__'] = g_git_last_update_message
        d['__debug_git_last_update_author_name__'] = g_git_last_update_author_name
        d['__debug_git_last_update_author_email__'] = g_git_last_update_author_email
        return d

    @staticmethod
    def get_host_name():
        """get host name

        :return: git infoascii
        :rtype: dict

        Usage::
        """
        v = 'unknown'
        try:
            v = str(os.popen('hostname').read()).replace('\n', '')
        except Exception as e:
            v = 'unknown'
        return v

    @staticmethod
    def get_host_ipv4():
        """
        :return: ipv4
        """
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 80))
            ipv4 = s.getsockname()[0]
        except Exception as e:
            ipv4 = '0.0.0.0'
        finally:
            s.close()

        return ipv4

    @staticmethod
    def get_debug_info():
        d = XUtils.get_git_info()
        d['__debug_host_ipv4__'] = XUtils.get_host_ipv4()
        d['__debug_host_name__'] = XUtils.get_host_name()
        return d

    @staticmethod
    def replace_text_in_file(p_target_file_path, p_matched_string, p_new_string):
        f = open(p_target_file_path, 'r')
        alllines = f.readlines()
        f.close()
        #
        f = open(p_target_file_path, 'w+')
        for eachline in alllines:
            a = re.sub(p_matched_string, p_new_string, eachline)
            f.writelines(a)
        f.close()
        return 'replace_text_in_file ok'

    @staticmethod
    def is_windows_os():
        return platform.system() == "Windows"

    @staticmethod
    def is_linux_os():
        return platform.system() == "Linux"

    @staticmethod
    def is_mac_os():
        return platform.system() == "Darwin"

    @staticmethod
    def python_major_version():
        """Get the major version of python
        :return:the major version of python, should be one of 2/3
        """
        return sys.version_info[0]
